import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
// DOM元素
const elements = {
    practiceList: document.getElementById('practiceList'),
    backButton: document.getElementById('backButton'),
    judgmentFilter: document.getElementById('judgmentFilter'),
    sortFilter: document.getElementById('sortFilter'),
    usernameDisplay: document.getElementById('username-display')
};

// 获取教师创建的练习列表
export async function getPractices(teacherId) {
    try {
        const response = await fetch(`/api/get-practices/${teacherId}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) {
            throw new Error(`获取练习列表失败: ${response.statusText}`);
        }

        return await response.json();
    } catch (error) {
        console.error('获取练习列表错误:', error);
        showError('获取练习列表失败，请稍后重试');
        return [];
    }
}

// 获取练习的提交记录
export async function getPracticeSubmissions(practiceId) {
    try {
        const response = await fetch(`/api/commited-practice/${practiceId}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) {
            throw new Error(`获取提交记录失败: ${response.statusText}`);
        }

        return await response.json();
    } catch (error) {
        console.error('获取提交记录错误:', error);
        showError('获取提交记录失败，请稍后重试');
        return [];
    }
}

// 显示练习提交记录
export async function displayPracticeSubmissions(teacherId, judgmentFilter = 'all', sortFilter = 'default') {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        await setupUserProfile(username);
        elements.practiceList.innerHTML = '<div class="text-center py-8"><i class="fas fa-spinner fa-spin text-blue-500 text-2xl"></i><p class="mt-2 text-gray-500">加载中...</p></div>';

        const practices = await getPractices(teacherId);
        let allSubmissions = [];

        // 获取所有练习的提交记录
        for (const practice of practices) {
            const submissions = await getPracticeSubmissions(practice.practice_id);
            allSubmissions = allSubmissions.concat(submissions.map(sub => ({
                ...sub,
                practice_name: practice.practice_name,
                course_name: practice.course_name
            })));
        }

        // 评阅状态过滤
        if (judgmentFilter === 'unjudged') {
            allSubmissions = allSubmissions.filter(submission => !submission.is_judged);
        }

        // 排序
        if (sortFilter === 'earliest') {
            allSubmissions.sort((a, b) => new Date(a.submit_time) - new Date(b.submit_time));
        }

        // 清空列表
        elements.practiceList.innerHTML = '';

        // 如果没有提交记录
        if (allSubmissions.length === 0) {
            elements.practiceList.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <h3>暂无需要批改的练习</h3>
                    <p>当前没有找到符合条件的练习提交</p>
                </div>
            `;
            return;
        }

        // 渲染提交记录
        allSubmissions.forEach(submission => {
            const practiceItem = document.createElement('div');
            practiceItem.className = 'practice-card';

            // 格式化日期
            const formattedDeadline = new Date(submission.deadline).toLocaleString();
            const formattedSubmitTime = new Date(submission.submit_time).toLocaleString();

            // 处理得分显示
            const scoreDisplay = submission.obtained_score !== undefined && submission.total_score !== undefined 
                ? `${submission.obtained_score}/${submission.total_score}` 
                : '未提交';

            // 处理评阅状态
            const judgmentStatus = submission.is_judged 
                ? '<span class="status-label status-judged"><i class="fas fa-check-circle mr-1"></i>已评阅</span>' 
                : '<span class="status-label status-unjudged"><i class="fas fa-exclamation-circle mr-1"></i>未评阅</span>';

                practiceItem.innerHTML = `
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-6 shadow-lg border-2 border-blue-200 mb-6 hover:shadow-xl transition-all">
                    <!-- 顶部标题区域 -->
                    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6 p-4 bg-white rounded-lg shadow-sm border border-blue-100">
                        <div>
                            <h3 class="text-2xl font-bold text-blue-800 flex items-center gap-2">
                                <i class="fas fa-file-alt text-blue-600"></i>
                                ${submission.practice_name}
                            </h3>
                            <p class="text-md text-blue-600 mt-2">
                                <i class="fas fa-book mr-2"></i>${submission.course_name}
                            </p>
                        </div>
                        <div class="flex flex-col items-end">
                            ${judgmentStatus}
                            <p class="text-sm text-blue-500 mt-2">
                                <i class="fas fa-id-card mr-1"></i>学生学号: ${submission.student_id}
                            </p>
                        </div>
                    </div>
                    
                    <!-- 信息卡片区域 -->
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                        <!-- 时间信息卡片 -->
                        <div class="bg-white p-4 rounded-lg shadow-sm border border-blue-100">
                            <div class="flex items-center gap-3 mb-3">
                                <div class="bg-blue-100 p-2 rounded-full text-blue-600">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <h4 class="text-lg font-semibold text-blue-700">时间信息</h4>
                            </div>
                            <div class="space-y-3">
                                <div class="flex items-center gap-2">
                                    <span class="text-blue-600 w-24">提交时间:</span>
                                    <span class="font-medium text-blue-800 bg-blue-50 px-3 py-1 rounded">${formattedSubmitTime}</span>
                                </div>
                                <div class="flex items-center gap-2">
                                    <span class="text-blue-600 w-24">截止时间:</span>
                                    <span class="font-medium text-blue-800 bg-blue-50 px-3 py-1 rounded">${formattedDeadline}</span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 学生信息卡片 -->
                        <div class="bg-white p-4 rounded-lg shadow-sm border border-blue-100">
                            <div class="flex items-center gap-3 mb-3">
                                <div class="bg-blue-100 p-2 rounded-full text-blue-600">
                                    <i class="fas fa-user-graduate"></i>
                                </div>
                                <h4 class="text-lg font-semibold text-blue-700">学生信息</h4>
                            </div>
                            <div class="space-y-3">
                                <div class="flex items-center gap-2">
                                    <span class="text-blue-600 w-24">姓名:</span>
                                    <span class="font-medium text-blue-800 bg-blue-50 px-3 py-1 rounded">${submission.name}</span>
                                </div>
                                <div class="flex items-center gap-2">
                                    <span class="text-blue-600 w-24">得分:</span>
                                    <span class="font-bold text-lg text-blue-700 bg-blue-50 px-3 py-1 rounded">${scoreDisplay}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 批改按钮 -->
                    <div class="flex justify-center">
                        <button class="grade-button w-full md:w-1/2 px-6 py-4 rounded-xl bg-gradient-to-r from-blue-600 to-blue-700 text-white font-bold hover:from-blue-700 hover:to-blue-800 transition-all flex items-center justify-center gap-3 shadow-lg hover:shadow-xl transform hover:-translate-y-1" 
                                data-practice-id="${submission.practice_id}" 
                                data-user-id="${submission.user_id}">
                            <i class="fas fa-edit text-xl"></i>
                            <span class="text-lg">批改此练习</span>
                        </button>
                    </div>
                </div>`;

            elements.practiceList.appendChild(practiceItem);
            
            // 添加点击事件
            const gradeButton = practiceItem.querySelector('.grade-button');
            gradeButton.addEventListener('click', () => {
                const practiceId = gradeButton.dataset.practiceId;
                const userId = gradeButton.dataset.userId;
                window.location.href = `check-practice.html?practiceId=${practiceId}&userId=${userId}&username=${username}`;
            });
        });
    } catch (error) {
        console.error('显示练习提交记录错误:', error);
        showError('加载练习提交记录失败，请稍后重试');
    }
}

// 显示错误信息
export function showError(message) {
    elements.practiceList.innerHTML = `
        <div class="error-message">
            <h3><i class="fas fa-exclamation-circle mr-2"></i>加载失败</h3>
            <p>${message}</p>
        </div>
    `;
}

// 防抖函数
export function debounce(func, delay) {
    let timer = null;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    };
}

// 初始化页面
async function init() {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');

        if (!username) {
            throw new Error('未获取到用户信息，URL参数中缺少username');
        }

        // 获取教师ID
        const userResponse = await fetch(`/user-info?username=${username}`);
        const userData = await userResponse.json();

        if (!userData.user_id) {
            throw new Error('用户信息中缺少user_id字段');
        }

        // 初始加载
        await displayPracticeSubmissions(userData.user_id);

        // 添加筛选器事件监听
        const handleFilterChange = debounce(() => {
            const selectedJudgment = elements.judgmentFilter.value;
            const selectedSort = elements.sortFilter.value;
            displayPracticeSubmissions(userData.user_id, selectedJudgment, selectedSort);
        }, 150);

        elements.judgmentFilter.addEventListener('change', handleFilterChange);
        elements.sortFilter.addEventListener('change', handleFilterChange);

        // 返回按钮事件
        elements.backButton.addEventListener('click', () => {
            window.location.href = 'practice.html' + window.location.search;
        });

    } catch (error) {
        console.error('初始化错误:', error);
        showError(error.message || '初始化失败，请检查网络连接或重新登录');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='practice.html'+window.location.search;
        });
    }
});
